package com.soft.action.admin;

import com.soft.model.Business;
import com.soft.model.User;
import com.soft.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: 商户管理
 **/
@Controller
@RequestMapping("/businessManager")
public class BusInessManagerAction {


    @Autowired
    private BusinessService businessService;



    // 跳转到商户管理界面
    @RequestMapping("toUserManager")
    public String toUserManager(Map<String, Object> map) {
        List<Business> users = businessService.getAll();
        map.put("users", users);
        return "admin/businessManager";

    }

    // 查询
    @RequestMapping("/search")
    public String search(String username, Map<String, Object> map, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();

        if (username != null && !"".equals(username)) {
            Business user = businessService.getByUserName(username);
            if (user == null) {
                System.out.println("商户不存在！");
                out.write(
                        "<script>alert('商户 不存在！');" + "window.location.href='/garbage-collection/userManager/toUserManager'</script>");
            } else {
                List<Business> users = new ArrayList<Business>();
                users.add(user);
                map.put("users", users);
                return "admin/businessManager";
            }

        } else {
            return "redirect:toUserManager";
        }
        return "redirect:toUserManager";
    }


    // 修改
    @RequestMapping("/update")
    public String update(User user) {
        if (user != null) {
            // 这个是更新入库的user
            Business newUser = businessService.getById(user.getId());

            if (user.getUsername() != null && !"".equals(user.getUsername())) {
                newUser.setUsername(user.getUsername());
                System.out.println("修改了商户 名");
            }
            if (user.getPassword() != null && !"".equals(user.getPassword())) {
                newUser.setPassword(user.getPassword());
                System.out.println("修改了密码");
            }
            if (user.getMoney() != null) {
                newUser.setMoney(user.getMoney());
                System.out.println("修改了积分");
            }
            businessService.update(newUser);
        }
        return "redirect:toUserManager";
    }

    @RequestMapping("/delete")
    public String delete(Integer id) {
        businessService.delete(id);
        return "redirect:toUserManager";
    }
}